//
//  BBAlertView.m
//  AlertViewTool
//
//  Created by XiaoMing on 16/2/24.
//  Copyright © 2016年 XiaoMing. All rights reserved.
//

#define kAlertWidth  280.0f
#define kAlertHeight 400.0f
#define KHeadImageWH 80.0f
#define KButtonWH    100.0f

//设备的宽高
#define kIPHONE_HEIGHT  [UIScreen mainScreen].bounds.size.height
#define kIPHONE_WIDTH   [UIScreen mainScreen].bounds.size.width

//边线为1.0的线宽
#define kLineOnePxHeight (1.0/[[UIScreen mainScreen] scale])
// 屏幕比例
#define kScreenScale [[UIScreen mainScreen] scale]

/**************** 方便16进制颜色取值 ****************/
#define UIColorFromRGB(hexValue) [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0 green:((float)((hexValue & 0xFF00) >> 8))/255.0 blue:((float)(hexValue & 0xFF))/255.0 alpha:1.0]
#define kUIColorFromRGB(hexValue, a) [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0 green:((float)((hexValue & 0xFF00) >> 8))/255.0 blue:((float)(hexValue & 0xFF))/255.0 alpha:a]

#import "BBAlertView.h"
#import <QuartzCore/QuartzCore.h>

@interface BBAlertView ()

@property (nonatomic, assign) BOOL leftLeave;

@end

@implementation BBAlertView

+ (CGFloat)alertWidth {
    return kAlertWidth;
}

+ (CGFloat)alertHeight {
    return kAlertHeight;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
    }
    return self;
}

/** 加手势 */
- (void)tapGestureRecognizer {
    [self removeFromSuperview];
}

//移除手势
- (void)dealloc {
    [self removeGestureRecognizer:_tap];
}

- (id)initWithImage:(UIImage  *)headImage
      initWithTitle:(NSString *)title
        contentText:(NSString *)content
        messageText:(NSString *)message
  centerbuttonTitle:(NSString *)centerTitle
{
    if (self = [super init]) {
        self.backgroundColor = UIColorFromRGB(0xff3131);
        self.layer.cornerRadius = 3.0f;
        self.clipsToBounds = YES;
        
        self.headImage = [[UIImageView alloc] initWithFrame:CGRectMake((kAlertWidth - KHeadImageWH)/2, 40, KHeadImageWH, KHeadImageWH)];
        self.headImage.clipsToBounds = YES;
        self.headImage.layer.cornerRadius = KHeadImageWH/2;
        self.headImage.image = headImage;
        self.headImage.image = [UIImage imageNamed:@"BB_AlertView_Image"];
        [self addSubview:self.headImage];
        
        self.alertTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headImage.frame) + 10, kAlertWidth, 20)];
        self.alertTitleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
        self.alertTitleLabel.textColor = [UIColor whiteColor];
        [self addSubview:self.alertTitleLabel];
        
        self.alertContentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.alertTitleLabel.frame) + 3, kAlertWidth, 20)];
        self.alertContentLabel.textColor = UIColorFromRGB(0x969696);
        self.alertContentLabel.font = [UIFont systemFontOfSize:12.0f];
        [self addSubview:self.alertContentLabel];
        
        self.alertMessageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.alertContentLabel.frame) + 20, kAlertWidth, 20)];
        self.alertMessageLabel.font = [UIFont boldSystemFontOfSize:16.0f];
        self.alertMessageLabel.textColor = [UIColor whiteColor];
        self.alertContentLabel.textAlignment = self.alertTitleLabel.textAlignment = self.alertMessageLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:self.alertMessageLabel];
        
        self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.btn.backgroundColor = [UIColor orangeColor];
        self.btn.frame = CGRectMake((kAlertWidth - KButtonWH)/2, CGRectGetMaxY(self.alertMessageLabel.frame) + 40, KButtonWH, KButtonWH);
        self.btn.layer.cornerRadius = KButtonWH/2;
        self.btn.clipsToBounds = YES;
        [self.btn setTitle:centerTitle forState:UIControlStateNormal];
        [self.btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.btn.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
        [self.btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.btn];
        
        self.alertTitleLabel.text = title;
        self.alertContentLabel.text = content;
        self.alertMessageLabel.text = message;
        
        UIButton *xButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [xButton setImage:[UIImage imageNamed:@"btn_close"] forState:UIControlStateNormal];
        xButton.frame = CGRectMake(0, 0, 32, 32);
        [xButton addTarget:self action:@selector(xBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:xButton];
        
    }
    return self;
}

/**
 *  X按钮点击事件
 */
- (void)xBtnClicked:(id)sender {
    _leftLeave = NO;
    [self dismissAlert];
    if (self.XBtnBlock) {
        self.XBtnBlock();
    }
}

/**
 *  拆红包按钮点击事件
 */
- (void)btnClicked:(id)sender {
    CAAnimation *myAnimationRotate     = [self animationRotate];
    CAAnimationGroup *animationGroup   = [CAAnimationGroup animation];
    animationGroup.delegate            = self;
    animationGroup.removedOnCompletion = NO;
    animationGroup.duration            = 1;
    animationGroup.timingFunction      = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animationGroup.repeatCount         = 1;//FLT_MAX;  //"forever";
    animationGroup.fillMode            = kCAFillModeForwards;
    animationGroup.animations          = [NSArray arrayWithObjects:myAnimationRotate, nil];
    [self.btn.layer addAnimation:animationGroup forKey:@"animationRotate"];
}

/**
 *  显示
 */
- (void)show {
    UIViewController *topVC = [self appRootViewController];
    self.frame = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, - kAlertHeight - 30, kAlertWidth, kAlertHeight);
    [topVC.view addSubview:self];
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.5;
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [self.layer addAnimation:animation forKey:nil];
}

/**
 *  移除
 */
- (void)dismissAlert {
    [self removeFromSuperview];
    if (self.dismissBlock) {
        self.dismissBlock();
    }
}

/**
 *  移除方法
 */
- (void)removeFromSuperview {
    [self.backView removeFromSuperview];
    self.backView = nil;
    UIViewController *topVC = [self appRootViewController];
    self.frame = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, CGRectGetHeight(topVC.view.bounds), kAlertWidth, kAlertHeight);
}

- (UIViewController *)appRootViewController {
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (newSuperview == nil) {
        return;
    }
    UIViewController *topVC = [self appRootViewController];
    
    if (!self.backView) {
        self.backView = [[UIView alloc] initWithFrame:topVC.view.bounds];
        self.backView.backgroundColor = [UIColor blackColor];
        self.backView.alpha = 0.6f;
        self.backView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    }
    [topVC.view addSubview:self.backView];
    
    //    _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer)];
    //    [self.backView addGestureRecognizer:_tap];
    
    self.frame = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, (CGRectGetHeight(topVC.view.bounds) - kAlertHeight) * 0.5, kAlertWidth, kAlertHeight);
    
    [super willMoveToSuperview:newSuperview];
}

/**
 *  创建动画
 */
- (CAAnimation *)animationRotate {
    CATransform3D rotationTransform  = CATransform3DMakeRotation(M_PI, 0, -1, 0);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.toValue      = [NSValue valueWithCATransform3D:rotationTransform];
    animation.duration     = 0.3;
    animation.autoreverses = YES;
    animation.cumulative   = YES;
    animation.repeatCount  = 1;
    animation.beginTime    = 0.1;
    animation.delegate     = self;
    return animation;
}

/**
 *  点击按钮,动画结束后,移除
 */
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    _leftLeave = YES;
    [self dismissAlert];
    if (self.btnBlock) {
        self.btnBlock();
    }
}

- (UIViewController *)viewController {
    UIResponder *res = self;
    while (res) {
        if ([res isKindOfClass: [UIViewController class]])
            return (UIViewController *)res;
        else
            res = [res nextResponder];
    }
    return nil;
}

/**
 *  颜色转图片
 */
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end
